package com.md.api.common.utils;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSONObject;
import com.md.api.config.WxMiniConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ImageUtils {


	public static final String appId = "wx48d4ec0d95af5ac8";
	public static final String secret = "e6a753ec1dbed024462993d993fc5f59";

	/**
	 * 生成二维码上传oss
	 * */
	public static String generate(String content) throws Exception{
		byte[] data = QrCodeUtil.generatePng(content,300,300);
		return AliOssUtil.uploadByteData2Oss(data, IdUtil.uuid()+".jpg",AliOssUtil.SYS);
	}

	/***
	 *
	 * 生成小程序码
	 * */
	public static String smallProgCode(String path,String userId) {
		try {
//			WxToken accessToken = WxUtil.getToken(appId, secret);
//			JSONObject data = new JSONObject();
//			data.put("path",path);
//			data.put("width", "430");
//			byte[] data2 = HttpUtils.doPostInputStream("https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken.getAccessToken(), data.toJSONString(), "UTF-8");
//			return AliOssUtil.uploadByteData2Oss(data2, userId+".jpg",AliOssUtil.QRCODE);

			WxToken accessToken = WxUtil.getToken(appId, secret);
			RestTemplate rest = new RestTemplate();
			String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken.getAccessToken();
			Map<String,Object> param = new HashMap<>();
			param.put("path",path);
			param.put("width", 430);
			param.put("auto_color", false);
			Map<String,Object> line_color = new HashMap<>();
			line_color.put("r", 0);
			line_color.put("g", 0);
			line_color.put("b", 0);
			param.put("line_color", line_color);
			MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
			HttpEntity requestEntity = new HttpEntity(param, headers);
			ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
//			log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + JSONObject.toJSONString(entity.getBody()));
			byte[] data2 = entity.getBody();
			return AliOssUtil.uploadByteData2Oss(data2, userId+".jpg",AliOssUtil.QRCODE);
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
